<template>
  <page-view class="shop-cart">
    <page-header title="购物车" :show-back="true"></page-header>
    <div class="content-box">
      <div class="cart-list" v-if="cartList.length > 0">
        <van-list
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
        >
          <van-swipe-cell v-for="item in cartList" :key="item.id">
            <van-checkbox
              v-model="item.isCheck"
              @click="addPay(item)"
            ></van-checkbox>
            <van-card
              :num="item.count"
              :price="item.price"
              :desc="item.food_desc"
              :title="item.food_name"
              class="goods-card"
              :thumb="item.food_img[0]"
            >
              <template #num>
                <van-stepper
                  v-model="item.count"
                  theme="round"
                  button-size="18"
                  disable-input
                  min="0"
                  @plus="foodCountPlus(item.id, item.count + 1)"
                  @minus="foodCountMinus(item.id, item.count - 1, item)"
                />
              </template>
            </van-card>
            <template #right>
              <van-button
                square
                text="删除"
                type="danger"
                class="delete-button"
                @click="deleteShopCartItem(item.id)"
              />
            </template>
          </van-swipe-cell>
        </van-list>
      </div>
    </div>
    <div class="cart-footer">
      <van-checkbox v-model="all" @click="checkAll">全选</van-checkbox>
      <div class="right">
        <div class="total">合计：{{ totalMoney }}</div>
        <button @click="pay">结算</button>
      </div>
    </div>
  </page-view>
</template>

<script setup>
import { reactive, ref, computed, onMounted, onUnmounted, inject } from "vue";
import api from "../utils/api";
import { useRouter } from "vue-router";
import { showConfirmDialog, showToast } from "vant";
const router = useRouter();
const BaseURL = inject("BaseURL");

// 购物车的展示
const loading = ref(false);
const finished = ref(false);
const pageIndex = ref(1);
const cartList = reactive([]);
const totalPage = ref(0);
const totalPrice = ref(0);
const getCart = async () => {
  let result = await api.shopCartInfo.findByUid(pageIndex.value);
  totalPage.value = result.totalPage;
  totalPrice.value = result.totalPrice;
  result.list.map((item) => {
    item.food_img = item.food_img.split(",").map((item) => BaseURL + item);
    cartList.push(item);
  });
  loading.value = false;
  finished.value = pageIndex.value >= totalPage.value;
};
getCart();

const onLoad = () => {
  if (pageIndex.value < totalPage.value) {
    pageIndex.value++;
    getCart();
  }
};

const foodCountPlus = async (id, count) =>
  await api.shopCartInfo.edit(id, count);
const foodCountMinus = async (id, count, item) => {
  try {
    if (count == 0) {
      await showConfirmDialog({
        title: "警告",
        message: "确定要删除吗？？？",
      });
      await api.shopCartInfo.delete(id);
      let index = cartList.findIndex((item) => item.id == id);
      if (index != -1) cartList.splice(index, 1);
    } else {
      await api.shopCartInfo.edit(id, count);
    }
  } catch (error) {
    item.count++;
  }
};

const deleteShopCartItem = async (id) => {
  try {
    await showConfirmDialog({
      title: "警告",
      message: "确定要删除吗？？？",
    });
    await api.shopCartInfo.delete(id);
    let index = cartList.findIndex((item) => item.id == id);
    if (index != -1) cartList.splice(index, 1);
  } catch (error) {}
};

const all = ref(false);
const checkAll = async () => {
  if (all.value === true) cartList.forEach((item) => (item.isCheck = true));
  else cartList.forEach((item) => (item.isCheck = false));
};
const addPay = async (item) => {
  if (item.isCheck === false) all.value = false;
  else if (item.isCheck === true) {
    let flag = true;
    for (let i = 0; i < cartList.length; i++) {
      // console.log(typeof cartList[i].isCheck);
      if (Boolean(cartList[i].isCheck) === false) {
        flag = false;
        break;
      }
    }
    all.value = flag;
  }
};
const totalMoney = computed(() => {
  let result = 0;
  cartList.forEach((item) => {
    if (item.isCheck === true || item.isCheck === 1)
      result += item.price * item.count;
  });
  return result.toFixed(2);
});
// 结算条件，至少有一件商品被选中
const pay = () => {
  let res = cartList.filter(
    (item) => item.isCheck === true || item.isCheck === 1
  );
  if (res.length === 0) showToast("请选择心仪的商品");
  else
    router.push({
      name: "checkOrder",
      query: { goods: JSON.stringify(res), totalMoney: totalMoney.value },
    });
};

// 转场时更新数据库中的isCheck
onUnmounted(async () => {
  let arr = [];
  for (const item of cartList) {
    if (item.isCheck === true || item.isCheck === 1) arr.push(item.id);
  }
  if (arr.length > 0) await api.shopCartInfo.setDefault(arr);
});
</script>

<style lang="scss" scoped>
.shop-cart {
  .content-box {
    flex: 1;
    overflow: auto;
  }
  .cart-footer {
    width: 100%;
    height: 50px;
    margin-bottom: 60px;
    display: flex;
    justify-content: space-between;
    padding: 0 5px;
    .right {
      display: flex;
      .total {
        line-height: 50px;
        color: red;
      }
      button {
        border: none;
        width: 100px;
        height: 40px;
        margin: 5px 15px;
        background-color: skyblue;
        font-size: 20px;
        color: white;
        border-radius: 10px;
      }
    }
  }
}
::v-deep(.van-swipe-cell__wrapper) {
  display: flex;
}
::v-deep(.van-checkbox) {
  overflow: unset;
  margin-left: 16px;
}
::v-deep(.delete-button) {
  height: 100%;
}
::v-deep(.van-card__title.van-multi-ellipsis--l2) {
  font-size: 18px;
  line-height: 24px;
}
::v-deep(.van-card__desc.van-ellipsis) {
  max-height: unset;
  white-space: normal;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}
</style>